with Ada.Text_IO; use Ada.Text_IO;
with System.Pool_Local;
with Ada.Unchecked_Deallocation;

package body BigNumberP is

   --procedure Delete_BigNumber is new Ada.Unchecked_Deallocation(BigNumber, BA);

   function StringToBigNumber (s : String) return BA is
      a : constant BA := new BigNumber (s'Range);
   begin
      for i in s'Range loop
         a (a'Last - i + 1) := NumberCharacter (s (i));
      end loop;
      return a;
   exception
      when Constraint_Error => return a;
   end StringToBigNumber;

   function BigNumberToString (b : BA) return String is
      result : String (b'Range);
   begin
      for i in reverse b'Range loop
         result (b'Last - i + 1) := Character (b (i));
      end loop;
      return result;
   end BigNumberToString;

   procedure BigNumberShow (b : BA) is
   begin
      Put_Line (BigNumberToString (b));
   end BigNumberShow;

   procedure BigNumberAdd (a : not null BA; b : not null BA; c : in out BA) is
      L : BA;
      S : BA;

   begin
      if a'Length > b'Length then
         L := a;
         S := b;
      else
         L := b;
         S := a;
      end if;

      declare
         result : array (Positive'First .. L'Length + 1) of
            Integer := (others => 0);
      begin
         for i in Positive'First .. S'Length loop
            result (i) := NumberCharacter'Pos (L (i)) +
               NumberCharacter'Pos (S (i)) - 2 * NumberCharacter'Pos ('0');
         end loop;
         for i in S'Length + 1 .. L'Length loop
            result (i) := NumberCharacter'Pos (L (i)) -
                           NumberCharacter'Pos ('0');
         end loop;
         for i in result'First .. L'Length loop
            if result (i) > 9 then
               result (i) := result (i) - 10;
               result (i + 1) := result (i + 1) + 1;
            end if;
         end loop;

         if result (result'Last) = 0 then
            c := new BigNumber (Positive'First .. L'Length);
         else
            c := new BigNumber (Positive'First .. L'Length + 1);
         end if;
         for i in c'Range loop
            c (i) := NumberCharacter'Val (result (i) +
                        NumberCharacter'Pos ('0'));
         end loop;
      end;
   end BigNumberAdd;

end BigNumberP;
